package cn.szq.concurrent.thread.countdownlatch;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;

/**
 * @ClassName: CyclicBarrierDemo
 * @Description:
 * @Author: szq
 * @Date: 2021-10-25 08:38:04
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        IntStream.rangeClosed(1, 6).forEach(t->{
            new Thread(new Task(t, cyclicBarrier)).start();
        });
    }

    static class Task implements Runnable{
        private int id;

        private CyclicBarrier cyclicBarrier;

        public Task(int id, CyclicBarrier cyclicBarrier){
            this.id = id;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            System.out.println("同学" + id + "现在从学校出发，前往自行车驿站。");
            try {
                Thread.sleep((long) (Math.random() * 10000));
                System.out.println("同学" + id + "到达了自行车驿站，开始等待其他人到达。");
                cyclicBarrier.await();
                System.out.println("同学" + id + "开始骑车。");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
